/*
 * Licensed under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.submarine.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;

/**
 * 
 * @file org.submarine.util.NetUtil.java
 *
 * 网络工具类
 * 
 * @author gaojian
 * @created 2013-8-17 下午11:14:20
 * @version 0.0.1
 * @since 0.0.1
 *
 */
public class NetUtil {
	
	private static final Logger logger = Logger.getLogger(NetUtil.class.getName());
	
	public static String getHost() {
		return getLocalAddress().getHostAddress();
	}
	
	private static InetAddress getLocalAddress() {
        InetAddress localAddress = null;
        try {
            localAddress = InetAddress.getLocalHost();
            if (isValidAddress(localAddress)) {
                return localAddress;
            }
        } catch (Throwable e) {
            logger.log(Level.WARNING,"����IPʧ��, " + e.getMessage(), e);
        }
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            if (interfaces != null) {
                while (interfaces.hasMoreElements()) {
                    try {
                        NetworkInterface network = interfaces.nextElement();
                        Enumeration<InetAddress> addresses = network.getInetAddresses();
                        if (addresses != null) {
                            while (addresses.hasMoreElements()) {
                                try {
                                    InetAddress address = addresses.nextElement();
                                    if (isValidAddress(address)) {
                                        return address;
                                    }
                                } catch (Throwable e) {
                                	logger.log(Level.WARNING,"����IPʧ��, " + e.getMessage(), e);
                                }
                            }
                        }
                    } catch (Throwable e) {
                    	logger.log(Level.WARNING,"����IPʧ��, " + e.getMessage(), e);
                    }
                }
            }
        } catch (Throwable e) {
        	logger.log(Level.WARNING, "����IPʧ��, " + e.getMessage(), e);
        }
        logger.log(Level.WARNING, "δ�ܵõ�����Ip��ַ����ʹ��127.0.0.1���档");
        return localAddress;
    }
 
    private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");
    
    private static final String LOCALHOST = "127.0.0.1";

    private static final String ANYHOST = "0.0.0.0";

    private static boolean isValidAddress(InetAddress address) {
        if (address == null || address.isLoopbackAddress())
            return false;
        String name = address.getHostAddress();
        return (name != null && ! ANYHOST.equals(name)
                && ! LOCALHOST.equals(name) && IP_PATTERN.matcher(name).matches());
    }

}
